<template>
  <div class="chat-container">
    <!-- 右侧聊天内容区域 -->
    <div class="chat-content-area">
      <!-- 聊天背景 -->
      <div class="chat-background"></div>
      <!-- 聊天内容 -->
      <div class="chat-content">
        <!-- 每条消息 -->
        <div v-for="(message, index) in messages" :key="index" class="message-item">
          <!-- 时间戳 -->
          <div class="timestamp">{{ message.timestamp }}</div>

          <!-- 消息气泡 -->
          <div class="message-bubble">
            <!-- 消息内容 -->
            <span v-if="!message.operate">{{ message.content }}</span>
            <el-input v-model="message.content" v-if="message.operate" />

            <el-icon
              :size="20"
              color="red"
              class="operate_btn"
              v-if="!message.operate"
              @click="editMessage(message)"
            >
              <Edit />
            </el-icon>
            <el-icon
              :size="20"
              color="blue"
              class="operate_btn"
              v-if="message.operate"
              @click="editDoneMessage(message)"
            >
              <Check />
            </el-icon>
            <!-- 操作按钮 -->
            <div class="actions">
              <div v-if="message.played" class="controls">
                <!-- <audio ref="audioPlayer" :src="currentAudioUrl" controls></audio> -->
              </div>
              <img
                v-if="message.played"
                src="@/assets/images/play2x.png"
                alt=""
                @click="playVoice(message)"
              />
              <img
                v-if="!message.played"
                src="@/assets/images/studed2x.png"
                alt=""
                @click="pauseVoice(message)"
              />
              <img
                v-if="!message.operate"
                src="@/assets/images/edit2x.png"
                alt=""
                @click="editMessage(message)"
              />
              <img
                v-if="message.operate"
                src="@/assets/images/edit2x.png"
                alt=""
                @click="editDoneMessage(message)"
              />
              <!--              <img src="@/assets/images/edit2x.png" alt="" @click="editMessage(message)" />-->
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="bottom">
      <div class="robotTalk" @click="toSpeechText">
        <span class="mr-5">生成原始记录</span>点这里
      </div>
      <div class="robot">
        <img src="~@/assets/images/robot.png" alt="机器人" />
      </div>
    </div>
  </div>
</template>

<script>
/* global webkitSpeechRecognition */
import axios from "axios";
export default {
  data() {
    return {
      // 模拟的消息数据
      messages: [],
      newMessage: "", // 新消息输入框
      isVoiceInputActive: false, // 控制语音输入状态
      recognition: null, // 语音识别实例
      newcontent: [
        {
          content: "请将上述内容以领导讲话的角度润色",
        },
      ],
      start: 0, // 初始 start 值
      end: 30, // 初始 end 值
      timer: null, // 定时器引用
      currentTime: "",
      duration: "",
      // globals: {
      //   webkitSpeechRecognition: 'readonly',
      // },
      currentAudio: null,
    };
  },
  mounted() {
    this.getAllModel();

    window.fieldId = this.$route.params.id;
    this.storeFieldIdInSessionStorage(window.fieldId);
    if ("webkitSpeechRecognition" in window) {
      this.recognition = new webkitSpeechRecognition();
      this.recognition.continuous = false;
      this.recognition.interimResults = false;
      this.recognition.lang = "zh-CN"; // 设置语言为中文

      this.recognition.onstart = () => {
        console.log("语音识别开始...");
      };

      this.recognition.onresult = (event) => {
        const transcript = event.results[0][0].transcript;
        this.messages.push({
          timestamp: this.formatTimestamp(),
          content: transcript,
        });
        this.newMessage = transcript; // 将识别结果填充到输入框
      };

      this.recognition.onerror = (event) => {
        console.error("语音识别错误:", event.error);
      };

      this.recognition.onend = () => {
        console.log("语音识别结束...");
        this.isVoiceInputActive = false;
      };
    } else {
      console.error("当前浏览器不支持语音识别功能");
    }
  },
  methods: {
    // 存储 fieldId 到 sessionStorage
    storeFieldIdInSessionStorage(fieldId) {
      sessionStorage.setItem("fieldId", fieldId);
    },
    //todo 获取单个语音文件转文字详情
    getAllModel() {
      const fid = this.$route.params.id;
      axios({
        method: "get",
        url: this.BaseApi + `/gt/util/queryfileinfo?fileid=` + fid,
        // data: 74,
      }).then((res) => {
        if (res.status === 200) {
          // const conText = res.data.split('\n')
          const conText = res.data.data;

          this.messages = conText.map((item) => {
            return {
              operate: false,
              played: true,
              timestamp:
                this.$convertToTime(item.start) + "-" + this.$convertToTime(item.end),
              content: item.data,
              id: item.id,
            };
          });
        } else {
          this.$message({
            showClose: true,
            message: "请求失败!",
          });
        }
      });
    },
    // 格式化时间戳
    formatTimestamp() {
      const now = new Date();
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      const seconds = String(now.getSeconds()).padStart(2, "0");
      return `${hours}:${minutes}-${hours}:${minutes}:${seconds}`;
    },
    // 播放语音
    playVoice(content) {
      if (this.currentAudio && content.currentTime) {
        // 从上次暂停的位置继续播放
        this.currentAudio.currentTime = content.currentTime;
        this.currentAudio.play();
        content.played = false;
      } else {
        // 首次播放
        content.played = false;
        const fid = this.$route.params.id;
        axios({
          method: "get",
          url: this.BaseApi + `/gt/util/streamaudiofile?fileid=` + fid,
          responseType: "blob",
        }).then((res) => {
          if (res.status === 200) {
            const audio = new Audio();
            const audioUrl = URL.createObjectURL(res.data);
            audio.src = audioUrl;
            this.currentAudio = audio;
            // 设置音频的持续时间
            audio.addEventListener("loadedmetadata", () => {
              content.duration = audio.duration;
            });
            // 设置音频的当前时间
            audio.currentTime = content.currentTime || 0;
            // 播放音频
            audio.play();
            // 更新当前时间
            audio.addEventListener("timeupdate", () => {
              content.currentTime = audio.currentTime;
            });
          } else {
            this.$message({
              showClose: true,
              message: "请求失败!",
            });
          }
        });
      }
    },

    // 暂停语音
    pauseVoice(content) {
      if (this.currentAudio && !this.currentAudio.paused) {
        // 暂停音频并记录当前播放位置
        this.currentAudio.pause();
        content.currentTime = this.currentAudio.currentTime;
        content.played = true;
      } else if (this.currentAudio) {
        // 继续播放
        this.currentAudio.play();
        content.played = false;
      }
    },
    // 编辑消息
    editMessage(content) {
      content.operate = true;
      // 打开编辑模式，显示输入框
      // content.editing = true;
      // content.originalContent = content.content; // 保存原始内容以便取消编辑时恢复
    },
    editDoneMessage(content) {
      content.operate = false;
      const fid = this.$route.params.id;
      axios({
        method: "post",
        url: this.BaseApi + `/gt/util/updatefileinfo`,
        data: {
          id: content.id.toString(),
          fileid: fid * 1,
          data: content.content,
        },
      }).then((res) => {
        if (res.status === 200) {
          this.$message({
            showClose: true,
            type: "success",
            message: "编辑成功!",
          });
        } else {
          this.$message({
            type: "error",

            showClose: true,
            message: "请求失败!",
          });
        }
      });
    },

    saveMessage(content) {
      // 保存编辑后的内容
      content.editing = false;
      this.$message.success("消息已保存");
    },
    cancelEdit(content) {
      // 取消编辑，恢复原始内容
      content.editing = false;
      content.content = content.originalContent;
    },
    // 删除消息
    deleteMessage(index) {
      this.messages.splice(index, 1);
      this.$message.success("消息已删除");
    },
    // 切换语音输入状态
    toggleVoiceInput() {
      if (!this.recognition) {
        console.error("语音识别功能不可用");
        return;
      }

      this.isVoiceInputActive = !this.isVoiceInputActive;

      if (this.isVoiceInputActive) {
        this.recognition.start();
      } else {
        this.recognition.stop();
      }
    },
    // 生成文档
    toSpeechText() {
      // 拼接所有消息内容
      const combinedContent = this.messages
        .map((message) => message.content)
        .join("\n\n"); // 用两个换行符分隔每条消息
      localStorage.setItem("speechToTextContent", combinedContent);
      this.$router.push({
        path: "/speechToText",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.chat-container {
  display: flex;
}

.audio-data-area {
  display: none;
  width: 30%;
  background-color: #061428;
  color: white;
  padding: 20px;
  box-sizing: border-box;
  border-right: 1px solid #096391;

  .audio-data-title {
    width: fit-content;
    font-size: 14px;
    margin-bottom: 20px;
    padding: 5px 10px;
    border-radius: 10px;
    box-sizing: border-box;
    background: rgba(250, 250, 250, 0.15);
    vertical-align: middle;
    margin-top: 8px;
    img {
      margin-right: 5px;
      vertical-align: middle;
    }
  }

  .audio-data-titleleft {
    width: fit-content;
    font-size: 14px;
    margin-bottom: 20px;
    padding: 5px 10px;
    border-radius: 10px;
    box-sizing: border-box;
    background: rgba(250, 250, 250, 0.15);
    vertical-align: middle;
    margin-top: 8px;
    img {
      margin-right: 5px;
      vertical-align: middle;
    }
  }

  .input-area {
    position: fixed;
    bottom: 20px;
    left: 2%; /* 根据左侧区域宽度调整 */
    width: 26%;
    padding: 10px;
    box-sizing: border-box;
    border: 1px solid #096391;
    height: 50px;
    border-radius: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .btns {
      width: 15%;
      cursor: pointer;
      img {
        margin-right: 10px;
      }
    }
    /deep/ .el-input__inner {
      background: none;
      color: #fff;
      border: none;
    }
  }
}
.speak_right {
  text-align: right;
  overflow: auto;
  height: 710px;
  .audio-data-title {
    float: right;
  }
}

.chat-content-area {
  width: 100%;
  position: relative;
  height: 100vh;
  overflow-y: auto;
  font-family: Arial, sans-serif;
  background-color: #061428;
}

.chat-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url("https://source.unsplash.com/random/1600x900/?space"); /* 替换为星空背景图片 */
  background-size: cover;
  filter: brightness(0.8); /* 调整亮度 */
}

.chat-content {
  padding: 20px;
  color: white;
}

.message-item {
  margin-bottom: 20px;
  position: relative;
  &::after {
    content: "";
    display: table;
    clear: both;
  }
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 10px;
}

.username {
  font-weight: bold;
  font-size: 22px;
  span {
    color: #3fb0ff;
  }
}

.message-bubble {
  background-color: rgba(45, 55, 67, 0.7);
  padding: 10px;
  border-radius: 10px;
}
.message-bubbleleft {
  background-color: rgba(45, 55, 67, 0.7);
  padding: 10px;
  border-radius: 10px;
}
.message-text {
  margin: 0;
  line-height: 25px;
  font-size: 14px;
}

.timestamp {
  font-size: 1em;
  color: #aaa;
  margin-bottom: 10px; /* 增加底部间距，避免与消息内容紧贴 */
}

.actions {
  margin-top: 5px;
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
  position: absolute;
  right: 10px;
  top: -5px;
  img {
    margin-right: 5px;
  }
}
.right_text {
  position: fixed;
  right: 20px;
  bottom: 10px;
  z-index: 10;
  cursor: pointer;
  .right_click {
    width: 166px;
    height: 60px;
    background: url("../../assets/images/talk2x.png") no-repeat center;
    background-size: 100% 100%;
    position: absolute;
    right: 65px;
    top: -55px;
    color: #fff;
    font-size: 18px;
    line-height: 50px;
    text-align: center;
    span {
      color: #3fb0ff;
      font-weight: 700;
    }
  }
}
.controls {
  display: flex;
  align-items: center;
  margin-top: 10px;

  input[type="range"] {
    width: 100%;
    margin-right: 10px;
  }
}
.bottom {
  height: 168px;
  position: absolute;
  bottom: 10px;
  right: 10px;
}
.robotTalk {
  position: absolute;
  top: 0px;
  right: 56px;
  width: 210px;
  height: 60px;
  background: url("~@/assets/images/robotTalk-bg.png") no-repeat;
  background-size: 100% 100%;
  box-sizing: border-box;
  padding: 14px 20px;
  font-size: 18px;
  cursor: pointer;
  color: #fff;

  span {
    font-weight: bold;
    color: #14b8fd;
  }
}

.robot {
  position: absolute;
  width: 87px;
  height: 114px;
  bottom: 0;
  right: 0;
}
.robot img {
  width: 100%;
  height: 100%;
  cursor: pointer;
}
</style>
